const axios = require('axios');
class KuaishouParser {
  constructor() {
    this.headers = {
      'User-Agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 14_0 like Mac OS X) AppleWebKit/605.1.15',
      'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
      'Accept-Language': 'zh-CN,zh;q=0.9',
      'Referer': 'https://www.kuaishou.com/'
    }
  }

  async parse(url, timeout) {
    try {
      const response = await axios.get(url, {
        timeout,
        headers: this.headers
      });
      const html = response.data;
      const scriptRegex = /"mainMvUrls"\s*:\s*(\[.*?\])/;
      const match = html.match(scriptRegex);
      if (match && match[1]) {
        try {
          const mainMvUrls = JSON.parse(match[1]);
          if (Array.isArray(mainMvUrls) && mainMvUrls.length > 0) {
            const videoUrl = mainMvUrls[0];
            return { data: { url: videoUrl } }
          }
        } catch (e) {
          console.error('解析mainMvUrls出错：', e);
        }
      }
    } catch (e) {
      return { code: 500, msg: `服务器错误：${e.message || "未知错误"}` };
    }
  }
}

module.exports = KuaishouParser;